package mp

import (
	"duoke/context"
	"duoke/internal/dao"
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/api345"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/gmd5"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/storage"
	"duoke/utils/valid"
	"duoke/utils/yaml"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/sirupsen/logrus"
	"net/http"
	"time"
)

var ShortVideo = new(shortvideoCtl)

type shortvideoCtl struct{}

func (ctl *shortvideoCtl) GatherVideo(c *gin.Context) {
	req := request.JsonMap(c)
	gatherUrl := gconv.String(req["gather_url"])
	if gatherUrl == "" {
		response.Error(c, "采集网址缺失", nil)
		return
	}
	// 开始采集
	jiexi, err := api345.NewConfig().Jiexi(gatherUrl)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	setting, err := service.Upload.Setting(c)
	// 这里存七牛云
	if setting.Type != "qiniu" {
		response.Error(c, "请配置七牛云上传方式", nil)
		return
	}
	// 七牛云保存
	// 定义日期格式
	dateFormat := "20060102"
	// 获取当前时间
	now := time.Now()
	// 按照指定格式格式化日期
	formattedDate := now.Format(dateFormat)
	imgUrl := gmd5.MustEncrypt(gconv.String(time.Now().Unix()) + jiexi.Data.Image)
	err = storage.Qiniu.UploadByURL(setting, "cbds/shortvideo/"+formattedDate, jiexi.Data.Image, imgUrl+".jpg")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}

	videoUrl := gmd5.MustEncrypt(gconv.String(time.Now().Unix()) + jiexi.Data.Video)
	err = storage.Qiniu.UploadByURL(setting, "cbds/shortvideo/"+formattedDate, jiexi.Data.Video, videoUrl+".video")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}

	c.JSON(http.StatusOK, gin.H{"msg": "success", "code": 1, "data": map[string]string{
		"title":  jiexi.Data.Title,
		"images": setting.Qiniu.Domain + "/cbds/shortvideo/" + formattedDate + "/" + imgUrl + ".jpg",
		"video":  setting.Qiniu.Domain + "/cbds/shortvideo/" + formattedDate + "/" + videoUrl + ".video",
	}})
}

func (ctl *shortvideoCtl) Save(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	shareType := gconv.Int(req["share_type"])
	err := service.Shortvideo.Watch(c, &model.VideoClick{
		ShortType: shareType,
		Id:        id,
	})
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	c.JSON(http.StatusOK, gin.H{"msg": "success", "code": 1, "data": nil})
}

// CreateOrder 创建订单
func (ctl *shortvideoCtl) CreateOrder(c *gin.Context) {
	req := request.JsonMap(c)
	userR, _ := service.User.Info(c, "openid,id,acid")
	id := gconv.Int(req["id"])
	if id == 0 {
		// 收费详情
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	info, err := service.Shortvideo.Info(id, "is_feel,total_amount,sub_mch_id,id")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	order, err := service.ShortOrder.InfoByWhere(fmt.Sprintf("short_video_id=%d and user_id=%d",
		info.Id, userR.Id), "order_no,id")
	if err == nil && order.Id != 0 {
		response.Success(c, "success", gin.H{
			"order_no": order.OrderNo,
		})
		return
	}
	if info.IsFeel != 1 {
		// 收费详情
		response.Error(c, "该视频为免费视频", nil)
		return
	}
	if info.SubMchId == "" {
		response.Error(c, "数据异常", nil)
		return
	}
	// 判断是否已经对该视频付款
	var shorOrder tables.ShortOrder
	_ = dao.ShortOrder.Ctx(c).Where("short_video_id=? and user_id =? and state = ?", id,
		userR.Id, 1).Scan(&shorOrder)
	if shorOrder.Id > 0 {
		response.Error(c, "该视频您已经购买过了", nil)
		return
	}
	now := time.Now()
	// 定义时间格式
	format := "20060102"
	// 将当前时间按照指定格式进行格式化
	formattedTime := now.Format(format)
	// 生产订单号
	orderNo := gconv.String(formattedTime) + gconv.String(time.Now().Local().Unix())
	// 未购买过 构造参数
	shorOrder = tables.ShortOrder{
		ShortVideoId: id,
		UserId:       userR.Id,
		TotalAmount:  info.TotalAmount,
		OrderNo:      orderNo,
		SubMchId:     info.SubMchId,
		IpAddr:       userR.IpAddr,
		Body:         "购买视频",
		Openid:       userR.Openid,
		State:        2,
		Acid:         userR.Acid,
	}
	_, err = dao.ShortOrder.Ctx(c).Save(&shorOrder)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{
		"order_no": orderNo,
	})
}

// PayOrder 订单支付
func (ctl *shortvideoCtl) PayOrder(c *gin.Context) {
	req := request.JsonMap(c)
	orderNo := gconv.String(req["order_no"])
	if orderNo == "" {
		response.Error(c, "订单号不能为空", nil)
		return
	}
	info, err := service.ShortOrder.Info(orderNo, "order_no",
		"short_video_id,total_amount,sub_mch_id,openid,body,order_no")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	config := yaml.GetConfig()
	if config.SubMch.SubType == "2" {
		info.SubMchId = ""
	}
	// 构建支付参数
	notifyUrl := context.Global.Domain + "/mp/notify/short_notify"
	payConf, err := service.WechatPay.OrderV2(c, notifyUrl, info.Openid, info.OrderNo,
		info.TotalAmount, info.Body, info.SubMchId)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", gin.H{
		"pay":      payConf,
		"order_no": info.OrderNo,
	})
}
func (ctl *shortvideoCtl) Info(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	if id == 0 {
		response.Error(c, "参数缺失【id】", nil)
		return
	}
	// 获取详情
	info, err := service.Shortvideo.Info(id, "*")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	//// 收费视频查看是否已购买
	//if info.TotalAmount > 0 {
	//	// 获取视频订单
	//	order, err := service.ShortOrder.MyShortVideoInfo(c, id, "id,state")
	//	if err != nil {
	//		response.Error(c, err.Error(), nil)
	//		return
	//	}
	//	if order.State != 1 {
	//		response.Error(c, "该付费视频你还没有购买", nil)
	//		return
	//	}
	//}
	// 观看 点赞 收藏
	err = service.Shortvideo.Watch(c, &model.VideoClick{
		ShortType: 3,
		Id:        id,
	})
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 统计
	//err = service.Shortvideo.Statistics(c, id)
	//if err != nil {
	//	response.Error(c, err.Error(), nil)
	//	return
	//}

	response.Success(c, "success", info)
}
func (ctl *shortvideoCtl) List(c *gin.Context) {
	var req model.ShortVideoReq
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	if req.PageNo == 0 {
		req.PageNo = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 15
	}
	list, total, err := service.Shortvideo.List(c, &req)
	if err != nil {
		logrus.Error(err.Error(), "获取视频列表失败")
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "获取成功", gin.H{"total": total, "list": list})
}
func (ctl *shortvideoCtl) ShortSave(c *gin.Context) {
	var req model.ShortReq
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if err := service.Shortvideo.Save(c, &req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", nil)
}
func (ctl *shortvideoCtl) ShortInfo(c *gin.Context) {
	req := request.JsonMap(c)
	id := gconv.Int(req["id"])
	info, err := service.Shortvideo.Info(id, "*")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	var mp []model.VideoRsp
	gjson.Json2StructOrMap(info.Pic, &mp)
	var mp1 []model.VideoRsp
	gjson.Json2StructOrMap(info.Video, &mp1)
	m := model.ShortRsp{
		Id:            info.Id,
		UserId:        info.UserId,
		Type:          info.Type,
		Title:         info.Title,
		Pic:           mp,
		Video:         mp1,
		BindType:      info.BindType,
		BindId:        info.BindId,
		Content:       info.Content,
		Kouling:       info.Kouling,
		StoreName:     info.StoreName,
		StoreLocation: info.StoreLocation,
		StoreTel:      info.StoreTel,
		GatherUrl:     info.GatherUrl,
		Dz:            info.Dz,
		Zf:            info.Zf,
		IsFeel:        info.IsFeel,
		TotalAmount:   info.TotalAmount,
		SubMchId:      info.SubMchId,
		Watch:         info.Watch,
	}
	response.Success(c, "success", &m)
}
func (ctl *shortvideoCtl) Del(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	if err := service.Shortvideo.Del(c, &req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", nil)
}
